<?php
include_once "mdbtable.php";

class MOper extends MDbTable {

	public $table = "operation";
	public $table_mass = "mass_operation";
	public $num = true;

	protected function _createSqlByFilters($filters)
	{
		$CI = &get_instance();
		$this->db->select('t.*');
		foreach($filters as $filter_key => $filter_value)
		{
			switch($filter_key)
			{
				case 'add_fields':
					foreach($filter_value as $f)
					{
						switch($f)
						{
							case "user_fio":
							case "user_email":
								$db_f = str_replace("user_", "", $f);
								$this->db->join($CI->MUser->table.' u', 'u.id = t.user_id');
								$this->db->select('u.'.$db_f.' '.$f);
								break;
						}
					}
					break;

				case 'user_parent_id':
					$CI = &get_instance();
					$this->db->join($CI->MUser->table.' u', 'u.id = t.user_id');
					$this->db->where('u.parent_id', intval($filter_value));
					unset($filters[$filter_key]);
					break;

				case 'depo_only':
					if($filter_value)
					{
						$this->db->where('if(type = "buy" or type = "ng" or type = "patriot" or type = "arest" or type = "8marta" or type = "modify.buy", depo > "", 1=1)', null, false);
					}
					unset($filters[$filter_key]);
					break;
			}
		}
		return parent::_createSqlByFilters($filters);
	}

	protected function _modifyRow(&$row)
	{
		list($year, $month, $day) = explode("-", $row['date']);
		$row['day'] = $day;
		$row['month'] = $month;
		$row['year'] = $year;
		parent::_modifyRow($row);
	}

	public function getMavroSumm($users_id, $opers_id = null)
	{
		global $VALUTA, $TYPE_OPER_SELL;
		$out = array();
		if(count($users_id))
		{
			$sql_id = is_array($opers_id) ? (count($opers_id) ? 'AND id IN ('.implode(', ', $opers_id).')' : 'AND id = -1') : '';
			$sql = "
SELECT
	user_id, 
	sum(mavro) mavro, 
	mavro_valuta, 
	percent
	
FROM
	(
		SELECT 
			user_id, 
			mavro_valuta, 
			percent, 
			mavro * if(type IN ('".implode("', '", $TYPE_OPER_SELL)."'), -1, 1) mavro
		FROM 
			".$this->db->dbprefix.$this->table." 
		WHERE 
			user_id IN (".implode(", ", $users_id).") 
			AND percent > 10
			".$sql_id."
	) o
GROUP BY
	user_id, mavro_valuta, percent
ORDER BY 
	percent ASC
";
			$rows = $this->db->query($sql)->result_array();
			$out_no_sort = array();
			foreach($rows as $row)
			{
				$out_no_sort[$row['user_id']][$row['mavro_valuta']][$row['percent']] = round($row['mavro'], 4);
				if($out_no_sort[$row['user_id']][$row['mavro_valuta']][$row['percent']] == 0)
				{
					unset($out_no_sort[$row['user_id']][$row['mavro_valuta']][$row['percent']]);
				}
			}
			foreach($out_no_sort as $u_id => $valutas)
			{
				foreach($VALUTA as $k => $v)
				{
					if(isset($valutas[$k]))
					{
						$out[$u_id][$k] = $valutas[$k];
					}
				}
			}
		}
		return $out;
	}

	public function getMavroByUser($users_id, $opers = null)
	{
		global $VALUTA;
		if(!is_array($opers))
		{
			$opers = $this->getList(array('user_id' => $users_id, 'sort' => 'percent asc'));
		}
		$mavro = array();
		foreach($opers as $oper)
		{
			if(!isset($mavro[$oper['mavro_valuta']][$oper['percent']]))
			{
				$mavro[$oper['mavro_valuta']][$oper['percent']] = 0;
			}
			$m = $oper['mavro'];
			if(!isBuy($oper))
			{
				$m *= -1;
			}
			$mavro[$oper['mavro_valuta']][$oper['percent']] = getFloat($mavro[$oper['mavro_valuta']][$oper['percent']] + $m);
			$mavro[$oper['mavro_valuta']][$oper['percent']] = round($mavro[$oper['mavro_valuta']][$oper['percent']], 4);
			if($mavro[$oper['mavro_valuta']][$oper['percent']] == 0)
			{
				unset($mavro[$oper['mavro_valuta']][$oper['percent']]);
			}
		}
		$mavro_sort = array();
		foreach($VALUTA as $k => $v)
		{
			if(isset($mavro[$k]))
			{
				ksort($mavro[$k]);
				$mavro_sort[$k] = $mavro[$k];
			}
		}
		return $mavro_sort;
	}

	public function insert($arr, &$id)
	{
		$arr['time_add'] = time();
		parent::insert($arr, $id);
		$arr['id'] = $id;
		operUpdateFrozen($arr);
	}

	public function save($arr, &$id)
	{
		$arr['time_update'] = time();
		parent::save($arr, $id);
	}

	public function delete($id)
	{
		$oper = $this->get($id);
		if(@$oper['id'] && !isBuy($oper) && $oper['parent_id'])
		{
			$parent = $this->get($oper['parent_id']);
			if(@$parent['id'])
			{
				$save = array();
				$save['ostatok'] = min(($parent['ostatok'] + $oper['mavro']), $parent['mavro']);
				$this->save($save, $parent['id']);
				$parent['ostatok'] = $save['ostatok'];
				operUpdateFrozen($parent);
			}
		}
		if($oper['type'] == 'sell.mass')
		{
			$bonuses_opers_id = $this->getMassFromOperId($id);
			if(count($bonuses_opers_id))
			{
				global $TYPE_OPER_SELL;
				$bonuses_opers = $this->getList(array('id' => $bonuses_opers_id));
				$update_ostatok = array();
				foreach($bonuses_opers as $b_oper)
				{
					$b_sales = $this->getList(array('parent_id' => $b_oper['id'], 'type' => $TYPE_OPER_SELL));
					if(count($b_sales))
					{
						$b_mavro = $b_oper['mavro'];
						foreach($b_sales as $b_s)
						{
							$b_mavro -= $b_s['mavro'];
						}
						$b_save = array('ostatok' => max(0, round($b_mavro, 4)), 'dop' => '');
						$this->save($b_save, $b_oper['id']);
					}
					else
					{
						$update_ostatok[] = $b_oper['id'];
					}
				}
				if(count($update_ostatok))
				{
					$sql = "UPDATE ".$this->db->dbprefix.$this->table." SET `ostatok` = `mavro`, `dop` = '' WHERE id IN (".implode(", ", $update_ostatok).")";
					$this->db->query($sql);
				}
			}
		}
		$this->db->delete($this->table_mass, array('from_oper_id' => $id));
		$this->db->delete($this->table_mass, array('to_oper_id' => $id));
		parent::delete($id);
	}

	public function addMass($from_oper_id, $to_oper_id, $date)
	{
		$from_oper_id =  is_array($from_oper_id) ? $from_oper_id : array($from_oper_id);
		if(count($from_oper_id))
		{
			$values = array();
			foreach($from_oper_id as $id)
			{
				$values[] = "('".$id."', '".$to_oper_id."')";
			}
			$sql = "INSERT INTO ".$this->db->dbprefix.$this->table_mass." ( `from_oper_id` , `to_oper_id` ) VALUES ".implode(", ", $values);
			$this->db->query($sql);

			$sql2 = "UPDATE ".$this->db->dbprefix.$this->table." SET `ostatok` = 0, `dop` = 'Продан ".getPrintDate($date)."' WHERE id IN (".implode(", ", $from_oper_id).")";
			$this->db->query($sql2);
		}
	}

	public function getMassFromOperId($to_oper_id)
	{
		$out = array();
		$rows = $this->db->get_where($this->table_mass, array('to_oper_id' => $to_oper_id))->result_array();
		foreach($rows as $row)
		{
			$out[] = $row['from_oper_id'];
		}
		return $out;
	}

	public function getMassToOperId($from_oper_id)
	{
		$rows = $this->db->get_where($this->table_mass, array('from_oper_id' => $from_oper_id))->result_array();
		$row = reset($rows);
		return @$row['to_oper_id'];
	}

	public function addComment($parent_id, $min_type, $comment)
	{
		$this->db->set('dop', 'concat(dop, if(dop <> "", "; ", ""), "'.$comment.'")', false);
		$this->db->where('parent_id = '.$parent_id.' and `type` > "'.$min_type.'" and `type` like "'.$min_type.'%"');
		$this->db->update($this->table);
	}

}

